import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { useUserStore } from '@/stores/modules/user'

class Request {
  private instance: AxiosInstance
  
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config)
    this.setupInterceptors()
  }
  
  private setupInterceptors() {
    // 请求拦截
    this.instance.interceptors.request.use((config) => {
      const userStore = useUserStore()
      if (userStore.token) {
        config.headers!.Authorization = `Bearer ${userStore.token}`
      }
      return config
    })
    
    // 响应拦截
    this.instance.interceptors.response.use(
      (response) => response.data,
      (error) => {
        return Promise.reject(error)
      }
    )
  }
  
  public request<T>(config: AxiosRequestConfig): Promise<T> {
    return this.instance.request(config)
  }
  
  public get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'GET', url })
  }
  
  public post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'POST', url, data })
  }
}

export const http = new Request({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000
})